<?php

namespace yunj\core;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use yunj\core\exception\GeneralException;

/**
 * 云静七牛云
 * Class YunjQiniu
 * @package yunj\core
 */
final class YunjQiniu {

    private $accessKey;

    private $secretKey;

    private $bucket;

    private $domain;

    // 上传key
    private $key;

    // 上传文件地址
    private $filePath;

    // 成功响应结果
    private $response;

    // 失败响应结果
    private $error;

    private function __construct() {
        $this->setAttr();
    }

    private function setAttr() {
        $this->validate = new Validate();
        // 验证是否引入composer 七牛云SDK
        if (!class_exists('\\Qiniu\\Auth')) throw new GeneralException('请通过composer引入七牛云SDK');
        $this->accessKey = yunj_setting('qiniu_access_key');
        $this->secretKey = yunj_setting('qiniu_secret_key');
        $this->bucket = yunj_setting('qiniu_bucket');
        $domain = yunj_setting('qiniu_domain');
        if (substr($domain, -1) == '/') $domain = substr($value, 0, -1);
        $this->domain = $domain;
    }

    private static $instance;

    public static function getInstance() {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Notes: 文件上传
     * Author: Uncle-L
     * Date: 2020/11/3
     * Time: 17:46
     * @param $key [上传的key]
     * @param $filePath [上传文件路径]
     * @return $this
     * @throws GeneralException
     * @throws \Exception
     */
    public function upload($key, $filePath) {
        $auth = new Auth($this->accessKey, $this->secretKey);
        $token = $auth->uploadToken($this->bucket);
        $uploadMgr = new UploadManager();
        list($response, $error) = $uploadMgr->putFile($token, $key, $filePath);
        if ($error) throw new GeneralException(is_string($error) ? $error : json_encode($error));
        $this->key = $key;
        $this->filePath = $filePath;
        $this->response = $response;
        $this->error = $error;
        return $this;
    }

    /**
     * Notes: 获取文件url
     * Author: Uncle-L
     * Date: 2020/11/3
     * Time: 17:47
     * @return string
     */
    public function url() {
        return $this->domain . '/' . $this->key;
    }

}